package com.bete.updata;

import static com.bete.updata.UpdateConstant.HTTPAPKURL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.DataOutputStream;
import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import me.jessyan.autosize.internal.CustomAdapt;
import me.jessyan.autosize.utils.LogUtils;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class UpdataActivity extends Activity implements CustomAdapt {

    String tempScreenShoftFilePath = "/sdcard/" + "screenshot.png";
    String tempHttpDonwnloadFilePath = "/sdcard/" + "temp.apk";
    String screenShotPng = "/sdcard/DCIM/screenshot.png";
    String intallPath;
    LinearLayout ll_layout;
    private ProgressDialog progressDialog;

    public enum ErrorType {
        TOAST, THROWEXCEOTION, SETRESULT
    }


    public ErrorType errorType = ErrorType.SETRESULT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        overridePendingTransition(0, 0);
        setContentView(R.layout.activity_updata);
        // 1. 创建一个文件的路径
        String apkFilePath = getIntent().getStringExtra(UpdateConstant.APKFILEPATH);
        String packagename = getIntent().getStringExtra(UpdateConstant.PACKAGENAME);
        String httpapkUrl = getIntent().getStringExtra(HTTPAPKURL);
        LogUtils.d(" httpapkUrl : " + httpapkUrl);
        String tempScreenPath = getIntent().getStringExtra(UpdateConstant.TEMPSCREENPATH);
        int timeouttime = getIntent().getIntExtra(UpdateConstant.TIMEOUTTIME, 6000);
        String tempDownloadFilePath = getIntent().getStringExtra(UpdateConstant.TEMPDOWNLOADFILEPATH);
        String softwareScreenshotsPath = getIntent().getStringExtra(UpdateConstant.SOFTWARESCREENSHOTSPATH);
        if (softwareScreenshotsPath == null || softwareScreenshotsPath.isEmpty()) {
            softwareScreenshotsPath = screenShotPng;
        }
        showProgressDialog(getString(R.string.shengjizhong));
        boolean softwareScreenshots = getIntent().getBooleanExtra(UpdateConstant.SOFTWARESCREENSHOTS, true);
        boolean installLoalApk = getIntent().getBooleanExtra(UpdateConstant.INSTALLLOALAPK, true);
        if (installLoalApk) {
            intallPath = apkFilePath;
        }
        ll_layout = findViewById(R.id.ll_layout);
        TextView tvUpdateVis = findViewById(R.id.tv_update_vis);
        ImageButton bt_back = findViewById(R.id.bt_back);
        bt_back.setVisibility(View.GONE);
        if (tempScreenPath != null && tempScreenPath.isEmpty()) {
            tempScreenShoftFilePath = tempScreenPath;
        }
        if (errorType == ErrorType.SETRESULT) {

            if (packagename == null || packagename.isEmpty()) {
                Intent intent = new Intent();
                intent.putExtra(UpdateConstant.ERRORMSG, getString(R.string.chuanshushujudeshihouqingshurubaoming));
                intent.setAction("com.bete.update.error");
                sendBroadcast(intent);
                restartApp(intallPath);
                finish();
//                setResult(RESULT_OK, intent);
//                finish();
                return;
            }
//            if (httpapkUrl == null || httpapkUrl.isEmpty() && !httpapkUrl.startsWith("http:")) {
//                Intent intent = new Intent();
//                intent.putExtra(UpdateConstant.ERRORMSG, getString(R.string.zaichuanshushujudeshihouqingxiedaixiazaidelianjie));
//                setResult(RESULT_OK, intent);
//                finish();
//                return;
//            }
            if (!FileCommonUtil.isFileExists(apkFilePath)) {
                Intent intent = new Intent();
                intent.putExtra(UpdateConstant.ERRORMSG, getString(R.string.zaichuanshushujudeshihouqingchuanshizhengqueqiecunzaidewenjianlujin));
                intent.setAction("com.bete.update.error");
                sendBroadcast(intent);
                restartApp(intallPath);
                finish();
                return;
            }

            // 本地文件安装路径
            if (apkFilePath == null || apkFilePath.isEmpty()) {
                Intent intent = new Intent();
                intent.putExtra(UpdateConstant.ERRORMSG, getString(R.string.chuanshushujudeshihouqingshurubaoming));
                intent.setAction("com.bete.update.error");
                sendBroadcast(intent);
                restartApp(intallPath);
                finish();
                return;
            }
            if (softwareScreenshots) {
                if (softwareScreenshotsPath != null && !softwareScreenshotsPath.isEmpty() && new File(softwareScreenshotsPath).exists()) {
                    // 1. 截取屏幕
                    File softwareScreenshotsFile = new File(softwareScreenshotsPath);
                    if (!softwareScreenshotsFile.isFile()) {
                        Intent intent = new Intent();
                        intent.putExtra(UpdateConstant.ERRORMSG, getString(R.string.zaichuanshushujudeshihouqingxiedaijietutuypian));
                        intent.setAction("com.bete.update.error");
                        sendBroadcast(intent);
                        restartApp(intallPath);
                        finish();
                        return;
                    } else {
                        // 判断截图路的文件是图片
                        if (isImageFile(softwareScreenshotsPath)) {
                            Bitmap bitmap = BitmapFactory.decodeFile(softwareScreenshotsPath);
                            // 将 Bitmap 转换为 Drawable
                            Drawable drawable = new BitmapDrawable(getResources(), bitmap);
                            // 设置背景到 View 中
                            ll_layout.setBackground(drawable);
                        } else {
                            Intent intent = new Intent();
                            intent.putExtra(UpdateConstant.ERRORMSG, getString(R.string.zaichaunshushujushiqingquebaoxiedaijietulujingshitupian));
                            intent.setAction("com.bete.update.error");
                            sendBroadcast(intent);
                            restartApp(intallPath);
                            finish();
                            return;
                        }
                    }
                } else {
                    // 将图片设置为全部白色的背景
                    ll_layout.setBackgroundColor(ContextCompat.getColor(this, R.color.white));

//                    Intent intent = new Intent();
//                    intent.putExtra(UpdateConstant.ERRORMSG, getString(R.string.zaichuanshushujudeshihouqingxiedaijietutuypian));
//                    setResult(RESULT_OK, intent);
//                    finish();
                }
            }
        }
        {
            LogUtils.d(" installLoalApk " + installLoalApk);
            if (installLoalApk) {
                intallPath = apkFilePath;
            } else {
                if (!FileCommonUtil.isFileExists(tempHttpDonwnloadFilePath)) {
                    if (errorType == ErrorType.THROWEXCEOTION) {
                        throw new UseErrorException(getString(R.string.weifaxianxiazaiwenjian));
                    } else if (errorType == ErrorType.TOAST) {
                        Toast.makeText(this, getString(R.string.weifaxianxiazaiwenjian), Toast.LENGTH_SHORT).show();
                    }
                }
                intallPath = tempHttpDonwnloadFilePath;
            }
            // 设置内容
            if (intallPath == null || intallPath.isEmpty()) {
                if (errorType == ErrorType.SETRESULT) {
                    Intent intent = new Intent();
                    intent.putExtra(UpdateConstant.ERRORMSG, getString(R.string.weifaxianxiazaiwenjian));
                    intent.setAction("com.bete.update.error");
                    sendBroadcast(intent);
                    restartApp(intallPath);
                    finish();
//                setResult(RESULT_OK, intent);

                } else if (errorType == ErrorType.TOAST) {
                    Toast.makeText(UpdataActivity.this, getString(R.string.weifaxianxiazaiwenjian), Toast.LENGTH_SHORT).show();
                } else if (errorType == ErrorType.THROWEXCEOTION) {
                    throw new UseErrorException(getString(R.string.weifaxianxiazaiwenjian));
                }

                return;

            }

            // 在服务启动时执行静默安装和应用重启操作
            new Thread(new Runnable() {
                @Override
                public void run() {
                    LogUtils.d(intallPath + "");
                    if (installApk(intallPath)) {
                        restartApp(intallPath);
                    } else {
                        if (errorType == ErrorType.SETRESULT) {
                            Intent intent = new Intent();
                            intent.putExtra(UpdateConstant.ERRORMSG, result[0].errorMsg);
                            intent.setAction("com.bete.update.error");
                            sendBroadcast(intent);
                            restartApp(intallPath);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    finish();
                                }
                            });

//                        setResult(RESULT_OK, intent);
                        } else if (errorType == ErrorType.TOAST) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(UpdataActivity.this, result[0].errorMsg, Toast.LENGTH_SHORT).show();
                                }
                            });
                        } else if (errorType == ErrorType.THROWEXCEOTION) {
                            throw new UseErrorException(result[0].errorMsg);
                        }
                    }

                }
            }).start();
        }

        tvUpdateVis.setOnClickListener(v -> {
            if (onContinueClick(10, 3000)) {
                bt_back.setVisibility(View.VISIBLE);
            }
        });
        bt_back.setOnClickListener(v -> {
            restartApp(intallPath);
            finish();


        });

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                if (errorType == ErrorType.TOAST) {
                    Toast.makeText(UpdataActivity.this, getString(R.string.changshijianweianzhuangchenggong), Toast.LENGTH_SHORT).show();
                    finish();
                } else if (errorType == ErrorType.THROWEXCEOTION) {
                    throw new UseErrorException(getString(R.string.changshijianweianzhuangchenggong));
                } else if (errorType == ErrorType.SETRESULT) {
                    Intent intent = new Intent();
                    intent.putExtra(UpdateConstant.ERRORMSG, getString(R.string.changshijianweianzhuangchenggong));
//                    setResult(RESULT_OK, intent);
                    intent.setAction("com.bete.update.error");
                    sendBroadcast(intent);
                    restartApp(intallPath);
                    finish();
                }
            }
        }, timeouttime); //在指定的日期运行一次定时任务


    }

    public boolean isImageFile(String filePath) {
        String lowerCaseFilePath = filePath.toLowerCase();
        return lowerCaseFilePath.endsWith(".jpg") || lowerCaseFilePath.endsWith(".jpeg") || lowerCaseFilePath.endsWith(".png") || lowerCaseFilePath.endsWith(".gif") || lowerCaseFilePath.endsWith(".bmp");
    }

    ShellUtils.CommandResult[] result = {null};

    // 静默安装APK
    private boolean installApk(String apkFilePath) {
        Process process = null;
        DataOutputStream os = null;
        try {
            LogUtils.d(apkFilePath);
            result[0] = ShellUtils.execCmd("pm install -r " + apkFilePath, true);
            LogUtils.d(result[0].toString() + "");
            if (result[0].result == -1) {
                result[0] = ShellUtils.execCmd("pm install -r " + apkFilePath, false);
                LogUtils.d(result[0].toString() + "");
            }
            return true;
        } catch (Exception e) {
            LogUtils.d(e.toString() + "");

            Intent intent = new Intent();
            intent.putExtra(UpdateConstant.ERRORMSG, e.toString());
            setResult(RESULT_OK, intent);
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (process != null) {
                    process.destroy();
                }
            } catch (Exception e) {
                LogUtils.d(e.toString() + "");
            }
        }
    }

    private static long[] mClicks = null;

    /**
     * @param len  需要监听几次点击事件数组的长度就为几
     * @param time 规定的时间
     * @return
     */
    public static boolean onContinueClick(int len, long time) {
        if (mClicks == null) {
            mClicks = new long[len];
        }
        //将mClicks数组内的所有记录的时间左移一个位置
        System.arraycopy(mClicks, 1, mClicks, 0, mClicks.length - 1);
        //获得当前系统已经启动的时间
        mClicks[mClicks.length - 1] = SystemClock.uptimeMillis();
        //点击的时间差小于time就认为是连续点击
        LogUtils.e("mClicks[0] + time : " + mClicks[0] + time);
        LogUtils.e("mClicks[0] + time SystemClock.uptimeMillis() : " + SystemClock.uptimeMillis());
        if ((mClicks[0] + time) >= SystemClock.uptimeMillis()) {
            mClicks = null;
            return true;
        }
        return false;
    }

    // 重新启动应用
    private void restartApp(String apkFilePath) {
        //1. 移除Launcher
        String packageName = getPackageNameFromApk(this, apkFilePath);
        LogUtils.d(" packageName is :" + packageName);
        Intent launchIntent = getPackageManager().getLaunchIntentForPackage(packageName);
        if (launchIntent != null) {
            // 清除栈并启动应用的启动 Activity
            launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            launchIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            startActivity(launchIntent);
            overridePendingTransition(0, 0);
        }

    }

    public static String getPackageNameFromApk(Context context, String apkFilePath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo packageInfo = pm.getPackageArchiveInfo(apkFilePath, PackageManager.GET_ACTIVITIES);
        if (packageInfo != null) {
            return packageInfo.packageName;
        }
        return null;
    }

    @Override
    public boolean isBaseOnWidth() {
        return false;
    }

    @Override
    public float getSizeInDp() {
        return 0;
    }

    /**
     * 显示进度对话框
     */
    public void showProgressDialog(String text) {
        closeProgressDialog();
        LogUtils.d("ProgressDialog:" + text);
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
        }
        progressDialog.setMessage(text);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }


    /**
     * 关闭进度对话框
     */
    public void closeProgressDialog() {
//        LogUtils.d("ProgressDialog close");
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }
}